<template>
	<view class="container">
		<!-- 状态显示 -->
		<view v-if="attendanceStatus !== null" class="status-card" :class="statusClass">
			<text>{{ statusText }}</text>
			<text>距离：{{ distance }}米</text>
			<text>位置：{{ currentAddress }}</text>
		</view>

		<!-- 地图 -->
		<map :latitude="currentLat" :longitude="currentLng" :markers="markers"
			style="width: 100%; height: 300px;"></map>

		<!-- 打卡按钮 -->
		<button class="punch-btn" :disabled="isPunching" @click="handlePunch">
			{{ isPunching ? '打卡中...' : '立即打卡' }}
		</button>

		<!-- 设备信息 -->
		<view class="device-info">
			<view>设备ID：{{ deviceId }}</view>
			<view>定位方式：{{ locationType }}</view>
		</view>
	</view>
</template>

<script>
	import {
		punchAttendance
	} from "@/api/system/attendance.js"

	export default {
		data() {
			return {
				currentLat: 0,
				currentLng: 0,
				currentAddress: '定位中...',
				distance: 0,
				attendanceStatus: null,
				isPunching: false,
				locationType: '未知',
				deviceId: '',
				targetLat: 39.90923,
				targetLng: 116.39147,
				markers: [],
				locationTimer: null,
			};
		},
		computed: {
			statusText() {
				const texts = ['打卡成功', '超出打卡范围', '不在考勤时段'];
				return this.attendanceStatus !== null ? texts[this.attendanceStatus] : '';
			},
			statusClass() {
				return this.attendanceStatus === 0 ? 'success' : 'error';
			}
		},
		mounted() {
			this.getDeviceInfo();
			this.startMockLocationWatch();
		},
		beforeDestroy() {
			clearInterval(this.locationTimer);
		},
		methods: {
			startMockLocationWatch() {
				this.getCurrentLocation(); // 首次定位
				this.locationTimer = setInterval(() => {
					this.getCurrentLocation();
				}, 10000); // 每10秒更新位置
			},

			getCurrentLocation() {
				const _this = this;
				uni.getLocation({
					type: 'gcj02',
					geocode: true, // H5 可能返回 address 为空，设置 geocode:true 可能有用
					success(res) {
						_this.currentLat = res.latitude;
						_this.currentLng = res.longitude;
						_this.locationType = res.type || (res.accuracy ? 'WIFI/GPS' : '未知');
						_this.currentAddress =
							`${res.address.province || ''}${res.address.city || ''}${res.address.street || ''}`;
						_this.distance = _this.calculateDistance(res.latitude, res.longitude, _this.targetLat,
							_this.targetLng);

						_this.markers = [{
								id: 0,
								latitude: _this.targetLat,
								longitude: _this.targetLng,
								title: '考勤点',
								iconPath: '/static/image/sign/target.png'
							},
							{
								id: 1,
								latitude: res.latitude,
								longitude: res.longitude,
								title: '我的位置',
								iconPath: '/static/image/sign/location.png'
							}
						];
					},
					fail(err) {
						console.error('定位失败：', err);
						let tip = '定位失败，请检查定位权限';
						// 浏览器环境特殊提示
						if (process.env.UNI_PLATFORM === 'h5') {
							tip = '浏览器未授权定位，请检查浏览器权限设置';
						}
						uni.showToast({
							title: tip,
							icon: 'none',
							duration: 3000
						});
					}
				});
			},

			async handlePunch() {
				if (this.isPunching) return;

				this.isPunching = true;
				try {
					const data = {
						latitude: this.currentLat,
						longitude: this.currentLng,
						address: this.currentAddress,
						deviceId: this.deviceId,
						timestamp: Date.now()
					};
					punchAttendance(data).then(res => {
						if (res.data.code !== '0') {
							this.$modal.msgError(res.data.msg || '打卡失败');
						} else {
							this.$modal.msgSuccess('打卡成功');
							uni.navigateBack();
						}
					})

				} catch (error) {
					console.error('打卡异常', error);
					uni.showToast({
						title: '打卡请求失败',
						icon: 'none'
					});
				} finally {
					this.isPunching = false;
				}
			},

			calculateDistance(lat1, lon1, lat2, lon2) {
				const R = 6371e3;
				const toRad = deg => (deg * Math.PI) / 180;
				const dLat = toRad(lat2 - lat1);
				const dLng = toRad(lon2 - lon1);
				const a = Math.sin(dLat / 2) ** 2 +
					Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
					Math.sin(dLng / 2) ** 2;
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				return Math.round(R * c);
			},
			async getDeviceInfo() {
				try {
					const info = await uni.getSystemInfo();
					if (info.length >= 1) {
						this.deviceId = info[1].deviceId || info[1].model || '未知设备';
					} else {
						this.deviceId = info.deviceId || info.model || '未知设备';
					}
				} catch (e) {
					console.warn('设备信息获取失败:', e);
					this.deviceId = '获取失败';
				}
			}
		}
	}
</script>
<style scoped>
	.container {
		padding: 20rpx;
	}

	.status-card {
		padding: 20rpx;
		border-radius: 10rpx;
		margin-bottom: 30rpx;
		display: flex;
		flex-direction: column;
	}

	.status-card.success {
		background-color: #e8f5e9;
		border: 1px solid #4caf50;
	}

	.status-card.error {
		background-color: #ffebee;
		border: 1px solid #f44336;
	}

	.punch-btn {
		margin-top: 40rpx;
		background-color: #2196f3;
		color: white;
		border-radius: 50rpx;
	}

	.device-info {
		margin-top: 30rpx;
		font-size: 24rpx;
		color: #757575;
	}
</style>